const logger = require("../utils/logger")
const mysqlUtil = require("../utils/mysqlUtil")
const commonModule = require("./common")
const moment = require('moment')

module.exports = {
    // 获取未读通知数量
    getUnreadNotificationCnt: async (io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        try {
            let sql = 'SELECT COUNT(1) cnt FROM tb_user_notification WHERE uid = ? AND sta = 0'
            let res = await mysqlUtil.execute(sql, [uid])
            callback({code: 0, message: 'success', data: res[0].cnt})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 获取通知列表
    getNotificationList: async(io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        // // 小于的id
        // let lessThan = params.lessThan || 0
        // // 大于的id
        // let greaterThan = params.greaterThan || 0
        // 每页的数量
        let pageCount = params.pageCount || 10
        let start = params.start || 0
        let sta = params.sta || 0

        try {
            let sql = 'SELECT * FROM tb_user_notification WHERE uid = ? AND sta = ? ORDER BY createTime DESC LIMIT ?, ?'
            let sqlParams = [uid, sta, start, pageCount]
            // if (lessThan) {
            //     sql = 'SELECT * FROM tb_user_notification WHERE uid = ? AND id < ? ORDER BY createTime DESC, sta ASC LIMIT ?'
            //     sqlParams = [uid, lessThan, pageCount]
            // } else if (greaterThan) {
            //     sql = 'SELECT * FROM tb_user_notification WHERE uid = ? AND id > ? ORDER BY createTime DESC, sta ASC LIMIT ?'
            //     sqlParams = [uid, greaterThan, pageCount]
            // } else {
            //     sql = 'SELECT * FROM tb_user_notification WHERE uid = ? ORDER BY createTime DESC, sta ASC LIMIT ?'
            //     sqlParams = [uid, pageCount]
            // }
            let res = await mysqlUtil.execute(sql, sqlParams)
            callback({code: 0, message: 'success', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    getNotificationListWeb: async(io, socket, params, callback) => {

        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        let pageIndex = parseInt(params.pageIndex || 1);
        let pageCount = parseInt(params.pageCount || 10);

        try {
            // 总数
            let res = await mysqlUtil.execute('SELECT COUNT(1) cnt FROM tb_user_notification WHERE uid = ?', [uid])
            let count = res[0].cnt
            // 未完成
            res = await mysqlUtil.execute('SELECT COUNT(1) cnt FROM tb_user_notification WHERE uid = ? AND sta = 0', [uid])
            let unRead = res[0].cnt
            // 列表
            let sql = 'SELECT * FROM tb_user_notification WHERE uid = ? ORDER BY id DESC LIMIT ?, ?'
            let params = [uid, (pageIndex - 1) * pageCount, pageCount]
            res = await mysqlUtil.execute(sql, params)
            callback({code: 0, message: 'success', data: {list: res, count, unRead}})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    getNotificationListWithStatusWeb: async (io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return callback({ code: 9999, message: '请重新登录' })

        let status = params.status || 0
        if (status !== 0 && status !== 1) {
            return callback({ code: -1, message: '参数错误' })
        }

        let pageNum = parseInt(params.pageNum || 1);
        let pageSize = parseInt(params.pageSize || 10);

        try {
            // 查询总数
            let res = await mysqlUtil.execute('SELECT COUNT(1) cnt FROM tb_user_notification WHERE uid = ? AND sta = ?', [uid, status])
            let count = res[0].cnt

            // 查询数据
            res = await mysqlUtil.execute('SELECT * FROM tb_user_notification WHERE uid = ? AND sta = ? ORDER BY id DESC LIMIT ?, ?', [uid, status, (pageNum - 1) * pageSize, pageSize])

            callback({code: 0, message: 'success', data: {list: res, count}})
        } catch (err) {
            logger.error(err)
            callback({ code: -1, message: 'system error'})
        }
    },

    // 获取通知详情
    getNotificationInfo: async(io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        if (!params.id) return callback({code: -1, message: '参数缺失'})

        try {
            let res = await mysqlUtil.execute('SELECT * FROM tb_user_notification WHERE id = ? LIMIT 1', [params.id])
            if (res.length == 0) return callback({code: -1, message: '通知不存在'})
            callback({code: 0, message: 'success', data: res[0]})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 阅读通知
    readNotification: async(io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        if (!params.id) return callback({code: -1, message: '参数缺失'})

        try {
            let res = await mysqlUtil.execute('UPDATE tb_user_notification SET sta = 1 WHERE id = ? LIMIT 1', [params.id])
            if (res.affectedRows == 0) return callback({code: -1, message: '通知不存在'})

            // 更新未读数量
            io.in(uid + '-app').emit('NOTIFICATION-CHANGE')
            io.in(uid + '-web').emit('NOTIFICATION-CHANGE')

            callback({code: 0, message: 'success'})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 新的会议通知
    newHuiyiTongzhi: async (io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        logger.debug('new meeting', params)

        if (!params.topic || !params.content || !params.meetingDate || !params.startTime || !params.endTime || !params.place || !params.xingshi || !params.host || !params.attenders) {
            return callback({code: -1, message: '参数缺失'})
        }

        if (!Array.isArray(params.attenders)) {
            return callback({code: -1, message: '参数错误'})
        }

        try {
            let sql = 'INSERT INTO tb_huiyi_tongzhi SET ?'
            let res = await mysqlUtil.execute(sql, [{
                uid,
                sta: 1,
                topic: params.topic,
                content: params.content,
                meetingDate: params.meetingDate,
                startTime: params.startTime,
                endTime: params.endTime,
                place: params.place,
                host: params.host,
                xingshi: params.xingshi,
                attenders: JSON.stringify(params.attenders),
                attaches: JSON.stringify(params.attaches || []),
                createTime: Date.now()
            }])

            let tongzhiId = res.insertId

            // 通知参加会议
            for (let i = 0; i != params.attenders.length; i++) {
                // 插入通知
                await mysqlUtil.execute('INSERT INTO tb_user_notification SET ?', [{
                    uid: params.attenders[i].uid, // 申请人的uid
                    typ: 20,
                    title: '会议通知',
                    content: '请准备参加会议',
                    sta: 0,
                    resTyp: 3,
                    relevenceId: tongzhiId,
                    createTime: Date.now()
                }])
                io.in(params.attaches[i] + '-app').emit('NOTIFICATION-CHANGE')
                io.in(params.attaches[i] + '-app').emit('NOTIFICATION-NEW')
                io.in(params.attaches[i] + '-web').emit('NOTIFICATION-CHANGE')
                io.in(params.attaches[i] + '-web').emit('NOTIFICATION-NEW')
            }

            callback({code: 0, message: 'success'})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    huiyiTongzhiRecord: async(io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        // 小于的id
        let lessThan = params.lessThan || 0
        // 大于的id
        let greaterThan = params.greaterThan || 0
        // 每页的数量
        let pageCount = params.pageCount || 10

        try {
            let sql = ''
            let sqlParams = []
            if (lessThan) {
                sql = 'SELECT * FROM tb_huiyi_tongzhi WHERE uid = ? AND id < ? ORDER BY id DESC LIMIT ?'
                sqlParams = [uid, lessThan, pageCount]
            } else if (greaterThan) {
                sql = 'SELECT * FROM tb_huiyi_tongzhi WHERE uid = ? AND id > ? ORDER BY id DESC LIMIT ?'
                sqlParams = [uid, greaterThan, pageCount]
            } else {
                sql = 'SELECT * FROM tb_huiyi_tongzhi WHERE uid = ? ORDER BY id DESC LIMIT ?'
                sqlParams = [uid, pageCount]
            }
            let res = await mysqlUtil.execute(sql, sqlParams)
            callback({code: 0, message: 'success', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    huiyiTongzhiRecordWeb: async(io, socket, params, callback) => {

        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return callback({code: 9999, message: '请重新登录'})


        let pageIndex = parseInt(params.pageIndex || 1);
        let pageCount = parseInt(params.pageCount || 10);

        try {
            let res = await mysqlUtil.execute('SELECT COUNT(1) cnt FROM tb_huiyi_tongzhi WHERE uid = ?', [uid])
            let count = res[0].cnt
            let sql = 'SELECT * FROM tb_huiyi_tongzhi WHERE uid = ? ORDER BY id DESC LIMIT ?, ?'
            let params = [uid, (pageIndex - 1) * pageCount, pageCount]
            res = await mysqlUtil.execute(sql, params)
            callback({code: 0, message: 'success', data: {list: res, count}})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    huiyiTongzhiDetail: async(io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        if (!params.id) return callback({code: -1, message: '参数错误'})

        try {
            let res = await mysqlUtil.execute('SELECT * FROM tb_huiyi_tongzhi WHERE id = ? LIMIT 1', [params.id])
            if (res.length == 0) return callback({code: -1, message: '不存在'})
            callback({code: 0, message: '', data: res[0]})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 新的工作通知
    newGongzuoTongzhi: async (io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        logger.debug('new gongzuo tongzhi', params)

        try {
            let sql = 'INSERT INTO tb_gongzuo_tongzhi SET ?'
            let res = await mysqlUtil.execute(sql, [{
                uid,
                zhuti: params.zhuti,
                neirong: params.neirong,
                lianjie: params.lianjie,
                pics: JSON.stringify(params.pics),
                attaches: JSON.stringify(params.attaches || []),
                readers: JSON.stringify(params.readers || []),
                createTime: Date.now()
            }])
            let tongzhiId = res.insertId

            for (let i = 0; i != params.readers.length; i++) {
                // 插入通知
                await mysqlUtil.execute('INSERT INTO tb_user_notification SET ?', [{
                    uid: params.readers[i].uid,
                    typ: 21,
                    title: '工作通知',
                    content: '请阅读工作通知',
                    sta: 0,
                    resTyp: 3,
                    relevenceId: tongzhiId,
                    createTime: Date.now()
                }])
                io.in(params.readers[i] + '-app').emit('NOTIFICATION-CHANGE')
                io.in(params.readers[i] + '-app').emit('NOTIFICATION-NEW')
                io.in(params.readers[i] + '-web').emit('NOTIFICATION-CHANGE')
                io.in(params.readers[i] + '-web').emit('NOTIFICATION-NEW')
            }

            callback({code: 0, message: 'success'})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },
    
    gongzuoTongzhiRecord: async(io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        // 小于的id
        let lessThan = params.lessThan || 0
        // 大于的id
        let greaterThan = params.greaterThan || 0
        // 每页的数量
        let pageCount = params.pageCount || 10

        try {
            let sql = ''
            let sqlParams = []
            if (lessThan) {
                sql = 'SELECT * FROM tb_gongzuo_tongzhi WHERE uid = ? AND id < ? ORDER BY id DESC LIMIT ?'
                sqlParams = [uid, lessThan, pageCount]
            } else if (greaterThan) {
                sql = 'SELECT * FROM tb_gongzuo_tongzhi WHERE uid = ? AND id > ? ORDER BY id DESC LIMIT ?'
                sqlParams = [uid, greaterThan, pageCount]
            } else {
                sql = 'SELECT * FROM tb_gongzuo_tongzhi WHERE uid = ? ORDER BY id DESC LIMIT ?'
                sqlParams = [uid, pageCount]
            }
            let res = await mysqlUtil.execute(sql, sqlParams)
            callback({code: 0, message: 'success', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    gongzuoTongzhiRecordWeb: async(io, socket, params, callback) => {

        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return callback({code: 9999, message: '请重新登录'})


        let pageIndex = parseInt(params.pageIndex || 1);
        let pageCount = parseInt(params.pageCount || 10);

        try {
            let res = await mysqlUtil.execute('SELECT COUNT(1) cnt FROM tb_gongzuo_tongzhi WHERE uid = ?', [uid])
            let count = res[0].cnt
            let sql = 'SELECT * FROM tb_gongzuo_tongzhi WHERE uid = ? ORDER BY id DESC LIMIT ?, ?'
            let params = [uid, (pageIndex - 1) * pageCount, pageCount]
            res = await mysqlUtil.execute(sql, params)
            callback({code: 0, message: 'success', data: {list: res, count}})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    gongzuoTongzhiDetail: async(io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        if (!params.id) return callback({code: -1, message: '参数错误'})

        try {
            let res = await mysqlUtil.execute('SELECT * FROM tb_gongzuo_tongzhi WHERE id = ? LIMIT 1', [params.id])
            if (res.length == 0) return callback({code: -1, message: '不存在'})
            callback({code: 0, message: '', data: res[0]})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    }
}
